21 #define D(x) cout << #x " is " << x << endl
22 const int MAXN
= 1000, MAXEDGE
= 10;
23 int g
[MAXN
][MAXN
], d
[MAXN
][MAXN
];
31 queue
<state
> q
[MAXEDGE
];
34 void enqueue(int i
, int j
, int w
){
35 q
[w
% MAXEDGE
].push((state
){i
, j
, w
});
38 bool dequeue(int &i
, int &j
, int &w
){
39 int started_at
= current_q
;
40 while (q
[current_q
].empty()){
41 current_q
= (current_q
+ 1)%MAXEDGE
;
42 if (current_q
== started_at
) return false;
44 const state
&s
= q
[current_q
].front();
45 i
= s
.i
, j
= s
.j
, w
= s
.w
;
52 for (int i
=0; i
<MAXEDGE
; ++i
){
53 for (; q
[i
].size(); q
[i
].pop());
57 enqueue(0, 0, g
[0][0]);
58 for (int i
, j
, w
; dequeue(i
, j
, w
); ){
59 //printf("popped (%d, %d, %d)\n", i, j, w);
60 if (w
> d
[i
][j
]) continue;
61 if (i
== rows
-1 && j
== cols
-1) break;
62 for (int di
=-1; di
<=1; ++di
){
63 for (int dj
=-1; dj
<=1; ++dj
){
64 if (di
!= 0 ^ dj
!= 0){
67 if (0 <= ni
&& ni
< rows
&& 0 <= nj
&& nj
< cols
){
68 int w_extra
= g
[ni
][nj
];
69 if (w
+ w_extra
< d
[ni
][nj
]){
70 d
[ni
][nj
] = w
+ w_extra
;
71 enqueue(ni
, nj
, w
+ w_extra
);
78 return d
[rows
-1][cols
-1];
83 for (scanf("%d", &how_many
); how_many
--; ){
84 scanf("%d %d", &rows
, &cols
);
85 for (int i
=0; i
<rows
; ++i
){
86 for (int j
=0; j
<cols
; ++j
){
87 scanf("%d", &g
[i
][j
]);
94 printf("%d\n", dijkstra());